package com.feicheng.lanniao.service.impl;

import com.feicheng.lanniao.entity.PayOrder;
import com.feicheng.lanniao.entity.PayOrderPagePOJO;
import com.feicheng.lanniao.exception.SystemException;
import com.feicheng.lanniao.mapper.order.OrderMapper;
import com.feicheng.lanniao.result.ResultInfo;
import com.feicheng.lanniao.service.order.OrderService;
import com.feicheng.lanniao.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @param clientId 用户id
     * @param date      订单生产时间
     * @param money     订单消费
     * @param description 订单描述
     * @description 支付成功后插入一条订单
     * @return
     */
    @Override
    public ResultInfo insertOrder(Integer clientId, Integer money, String description) {
        log.info("OrderServiceImpl的insertOrder方法进入,参数clientId为"+clientId,",参数money为"+money+
                ",参数description为"+description);
        //格式化日期
        String format = formatter.format(LocalDateTime.now());
        //插入一条订单信息
        Integer insertCount = orderMapper.insertOrder(clientId, format, money, description);
        //参数校验
        if(insertCount != 1){
            throw new SystemException("插入订单信息失败");
        }
        return ResultInfo.success();
    }

    /**
     * @param clientId 用户Id
     * @description 根据用户Id查询订单列表
     * @return
     */
    @Override
    public ResultInfo selectPayOrderListByClientId(Integer clientId,Integer page,Integer size) {
        log.info("OrderServiceImpl的selectPayOrderListByClientId方法进入,参数clientId为"+clientId);
        //分页查询
        List<PayOrder> payOrders = orderMapper.selectPayOrderListByClientId(clientId,page,size);

        //查询出有多少条
        Integer selectCount = orderMapper.selectCountPayOrderListByClientId(clientId);

        PayOrderPagePOJO payOrderPagePOJO = new PayOrderPagePOJO();
        payOrderPagePOJO.setPage(page);
        payOrderPagePOJO.setSize(size);
        payOrderPagePOJO.setTotalCount(selectCount);
        payOrderPagePOJO.setTotalPage(PageUtil.getTotalPage(selectCount,size));
        payOrderPagePOJO.setPayOrderList(payOrders);

        return ResultInfo.success(payOrderPagePOJO);
    }
}
